import { defineStore } from "pinia";

export const tabsStore = defineStore("tabsStore", {
  state: () => ({
    visitedViews: [] as any[],
    cachedViews: [] as any[],
  }),
  actions: {
    addView(view: any, language: string = "") {
      // 标准化路径：移除语言前缀
      let normalizedPath = view.path;
      if (!isCnLocale(language)) {
        const idx = view.path.indexOf("/", 2);
        if (idx !== -1) {
          normalizedPath = view.path.substring(idx);
        }
      }
      
      // 检查是否已存在
      if (this.visitedViews.some((value) => value.path === normalizedPath)) {
        return;
      }
      
      console.log('view', view);
      this.visitedViews.push(
        Object.assign({}, view, {
          path: normalizedPath, // 使用标准化后的路径
          title: view.meta?.title || "unknown",
        })
      );
    },
    addCachedView(view: any) {
      if (this.cachedViews.includes(view.name)) {
        return;
      }

      if (view.meta.cache) {
        this.cachedViews.push(view.name);
      }
    },
    delView(view: any) {
      for (const [i, v] of this.visitedViews.entries()) {
        if (v.path == view.path) {
          this.visitedViews.splice(i, 1);
          break;
        }
      }
      this.delCachedView(view).then();
    },
    delCachedView(view: any) {
      return new Promise((resolve) => {
        const index = this.cachedViews.indexOf(view.name);
        if (index > -1) {
          this.cachedViews.splice(index, 1);
        }
        resolve([...this.cachedViews]);
      });
    },
    delOthersViews(view: any) {
      this.visitedViews = this.visitedViews.filter((v) => {
        return v.meta.affix || v.path === view.path;
      });

      const index = this.cachedViews.indexOf(view.name);
      if (index > -1) {
        this.cachedViews = this.cachedViews.slice(index, index + 1);
      } else {
        this.cachedViews = [];
      }
    },
    delAllViews() {
      this.visitedViews = this.visitedViews.filter((tab) => tab.meta.affix);
      this.cachedViews = [];
      console.log("this.visitedViews", this.visitedViews);
      console.log("this.cachedViews", this.cachedViews);
    },
  },
});
